package com.example.mahao_final.UI

import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.example.mahao_final.R
import com.example.mahao_final.database.UserDatabase
import com.example.mahao_final.entity.User
import com.example.mahao_final.utils.PasswordUtils
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class RegisterActivity : AppCompatActivity() {

    private lateinit var userDatabase: UserDatabase

    // 声明视图组件
    private lateinit var registerButton: Button
    private lateinit var usernameEditText: EditText
    private lateinit var passwordEditText: EditText
    private lateinit var confirmPasswordEditText: EditText
    private lateinit var nicknameEditText: EditText

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_register)

        // 使用 findViewById 绑定视图组件
        registerButton = findViewById(R.id.register_button)
        usernameEditText = findViewById(R.id.username_edit_text)
        passwordEditText = findViewById(R.id.password_edit_text)
        confirmPasswordEditText = findViewById(R.id.confirm_password_edit_text)
        nicknameEditText = findViewById(R.id.nickname_edit_text)

        userDatabase = UserDatabase.getDatabase(applicationContext)

        // 设置注册按钮的点击事件
        registerButton.setOnClickListener {
            val username = usernameEditText.text.toString()
            val password = passwordEditText.text.toString()
            val confirmPassword = confirmPasswordEditText.text.toString()
            val nickname = nicknameEditText.text.toString()

            // 1. 检查密码强度
            if (!isPasswordStrong(password)) {
                Toast.makeText(this, "密码强度不足，密码至少包含8个字符，并且包含大小写字母和数字", Toast.LENGTH_LONG).show()
                return@setOnClickListener
            }

            // 2. 检查密码是否一致
            if (password != confirmPassword) {
                Toast.makeText(this, "密码不一致，请重新输入", Toast.LENGTH_SHORT).show()
            } else if (username.isNotEmpty() && password.isNotEmpty() && nickname.isNotEmpty()) {
                // 异步检查用户名是否已存在
                CoroutineScope(Dispatchers.IO).launch {
                    val existingUser = userDatabase.userDao().getUserByUsername(username)

                    withContext(Dispatchers.Main) {
                        if (existingUser != null) {
                            // 如果用户名已存在，提示用户
                            Toast.makeText(this@RegisterActivity, "用户名已存在，请选择其他用户名", Toast.LENGTH_SHORT).show()
                        } else {
                            // 如果用户名不存在，继续注册
                            val hashedPassword = PasswordUtils.hashPassword(password)

                            // 创建用户对象
                            val user = User(username = username, password = hashedPassword, nickname = nickname)

                            // 异步执行注册操作
                            CoroutineScope(Dispatchers.IO).launch {
                                userDatabase.userDao().insertUser(user)
                                withContext(Dispatchers.Main) {
                                    Toast.makeText(this@RegisterActivity, "注册成功", Toast.LENGTH_SHORT).show()
                                    finish()  // 注册成功后关闭当前页面
                                }
                            }
                        }
                    }
                }
            } else {
                Toast.makeText(this, "请填写所有字段", Toast.LENGTH_SHORT).show()
            }
        }
    }

    // 密码强度验证方法
    private fun isPasswordStrong(password: String): Boolean {
        // 正则表达式：密码至少包含 8 个字符，且包含大小写字母和数字
        val passwordPattern = "^(?=.*[A-Z])(?=.*[a-z])(?=.*\\d).{8,}$"
        return password.matches(passwordPattern.toRegex())
    }
}
